/**
 * @author liuxl
 */
Ext.ux.UserPanel = function(){
	if (!checkPermission()) {
		return false;
	}
       var desktop = MyDesktop.getDesktop();
        var win = desktop.getWindow('user_grid_win');
        var windowId = 6;
        if (!win) {
            //定义一个 工具函数 来显示是否付费											
            var fuFeiRenderer = function(value){
                if (value == 1) {
                    return '<span style="color:red;font-weight:bold;">是</span>';
                }else {
                    return '<span style="color:green;font-weight:bold;">否</span>';
                }
            };
            var sm = new Ext.grid.CheckboxSelectionModel();
            //定义一个JsonReader对象，用于表格列表数据显示，即grid对象
            // simple array store
            var storeAdmin = new Ext.data.SimpleStore({									
                fields: ['name', 'code'],
                data: [["0", "0"], ["0", "0"]]
            });
			
			  //定义一个网站列表对像
        var ds_webSite_select = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({
                url: 'admin/user.jhtml?method=userList'
            }),
            reader: new Ext.data.JsonReader({
                root: 'results'
            }, [{
                name: 'websiteId'
            }, {
                name: 'websiteName',
                type: 'string'
            }])
        });
				  //定义一个网站列表对像
        var parentStore = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({
                url: 'admin/permission.jhtml?method=permissionParentList'
            }),
            reader: new Ext.data.JsonReader({
                root: 'results'
            }, [{
                name: 'permissionId'
            }, {
                name: 'permissionName',
                type: 'string'
            }])
        });
            var _jsonReader = null;
            //管理员管理
            if (windowId == 6) {
                _jsonReader = new Ext.data.JsonReader({
                    root: 'results'
                    //successProperty : 'success'
                   // totalProperty: 'totalCount'
                }, [{
                    name: 'usersId',
                    mapping: 'usersId'
                }, {
                    name: 'usersLoginName',
                    mapping: 'usersLoginName'
                }, {
                    name: 'isUsersAdmin',
                    mapping: 'isUsersAdmin'
                }, {
                    name: 'usersWebsiteId',
                    mapping: 'usersWebsiteId'
                }, {
                    name: 'usersDesc',
                    mapping: 'usersDesc'
                }, {
                    name: 'usersEmail',
                    mapping: 'usersEmail'
                }]);
            }
            var ds = null;
            //管理员管理
            if (windowId == 6) {
				ds = new Ext.data.Store({
                    proxy: new Ext.data.HttpProxy({
                        url: 'admin/user.jhtml?method=userList'
                    }),
                    reader: _jsonReader
                });
            }
          
			
            //定义列头信息
            var cm = null;
            //管理员管理
            if (windowId == 6) {
                cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), sm, {
                    header: "用户编号",
                    width: 50,
                    sortable: true,
                    dataIndex: 'usersId'
                }, {
                    header: "用户名称",
                    width: 100,
                    sortable: true,
                    dataIndex: 'usersLoginName'
                }, 
                 {
                    header: "描述",
                    width: 100,
                    dataIndex: 'usersDesc'
                }, {
                    header: "电子邮件",
                    width: 100,
                    sortable: true,
                    dataIndex: 'usersEmail'
                }]);
            }
            //开始创建Add面板
            var addForm = null;
            var userId = 0;
            //管理员管理ADD
            ////////////////////////////
            if (windowId == 6) {
               
                addForm = new Ext.FormPanel({
                    layout: 'column',
                    border: false,
                    labelSeparator: '：',
                    frame: true,
                    labelWidth: 80,
                    labelAlign: 'left',
                    buttonAlign: 'right',
                    bodyStyle: 'padding:5px',
                    width: 600,
                    fileUpload: true, //允许上传文件
                    items: [{
                        layout: 'column',
                        items: [{
                            columnWidth: .5,
                            layout: 'form',
                            items: [{
                                xtype: 'textfield',
                                fieldLabel: '用户名',
                                name: 'user_name',
                                //width:200
								maxLength:50,
						        maxLengthText:'名称不能超过50个字符',
                                allowBlank: false,
                                blankText: '用户名不能为空！',
                                anchor: '96%'
                            }, {
                                xtype: 'textfield',
                                inputType: 'password',
                                fieldLabel: '密码',
                                id:'pass1',
                                name: 'password',
                                maxLength: 15,
                                maxLengthText: '密码长度不能超过15位!',
                                minLength: '6',
                                minLengthText: '密码长度不能少于6位!',
                                allowBlank: false,
                                blankText: '密码不能为空',
                                anchor: '96%'
                            },    {
                                xtype: 'textfield',
                                fieldLabel: '电子邮件',
                                name: 'email',
                                vtype: 'email',
                                emailText: 'email格式不正确!!',               
                                //width:200
                                anchor: '96%'
                            }, {
                                xtype: 'textarea',
                                fieldLabel: '描述',
                                name: 'desc',
                                width: 200,
                                height: 100
                            
                            }]
                        }, {
                            columnWidth: .5,
                            layout: 'form',
                            items: [{
                                xtype: 'radiogroup',
								fieldLabel: '是否超管',
								items: [
									{boxLabel: '是', name: 'isUsersAdmin', inputValue: 1, checked: true},
									{boxLabel: '否', name: 'isUsersAdmin', inputValue: 0}
								]
                            }, {
                                xtype: 'textfield',
                                inputType: 'password',
                                fieldLabel: '确认密码',
                                id:'pass2',
                                name: 'repassword',                              
                                maxLength: 15,
                                maxLengthText: '密码长度不能超过15位!',
                                minLength: '6',
                                minLengthText: '密码长度不能少于6位!',
                                allowBlank: false,
                                blankText: '密码不能为空',                                                                                            
                                invalidText: '两次密码不一致！',
                                validator: function() {
                                if (Ext.get('pass1').dom.value == Ext.get('pass2').dom.value) {
                                 return true;
                                } else {
                                  return false;
                                  }
                                },
                                 anchor: '96%'                              
                            },  {
                                xtype: 'textfield',
                                fieldLabel: '移动电话',
                                name: 'mobile',
                                vtype: 'alphanum',
                                alphanumMask: '只能输入数字!!',
                                regex : /^1\d{10}$/,
                                regexText:"请输入正确的手机号码!",   
                                anchor: '96%'
                            
                            }]
                        }]
                    }],
                    buttons: [{
                        id: 'btnSave',
                        text: '保 存',
                        handler: function(){
                            if (addForm.form.isValid())//客户端先验证数据
                            {
                            
                                // this.disabled = true; //禁止保存按钮，防止多次提交
                                var ok = "123";
                                addForm.form.doAction('submit', {
                                    url: 'admin/user.jhtml?method=saveUser',
                                    method: 'post',
                                    waitTitle: '请稍候',
                                    waitMsg: '正在提交表单数据，请稍候...',
                                    params: {
                                        tishi: ok
                                    },
                                    success: function(form, action){
                                    	getAlertMessage("提示","操作成功!",Ext.MessageBox.WARNING);
                                        addForm.form.reset();
                                        this.disabled = false;
                                        newwin.hide();
                                        loadDs(ds,100);
                                    },
                                    failure: formError
                                })
                            }
                        }
                        
                    }, {
                        text: '取 消',
                        handler: function(){
                            newwin.hide();
                        }
                    }]
                });
            }
           
            ///over
            function showAddPanel(){
                newwin = new Ext.Window({
                    xtype: 'window',
                    title: '添加信息',
                    buttonAlign: 'right',
                    closable: true,
                    layout: 'fit',
                    modal: 'true',
                    width: 623,
                    height: 263,
                    closeAction: 'hide',
                    plain: true,
                    items: [addForm]
                
                });
                newwin.show();
            };
            //开始创建edit面板
            
            var editForm = null;
            ///////////////////////////////
            //管理员管理edit
            if (windowId == 6) {
                editForm = new Ext.FormPanel({
                    layout: 'column',
                    border: false,
                    labelSeparator: '：',
                    frame: true,
                    labelWidth: 80,
                    labelAlign: 'left',
                    buttonAlign: 'right',
                    bodyStyle: 'padding:5px',
                    width: 600,
                    reader: new Ext.data.JsonReader({
                        root: 'results'
                    }, ['usersId', 'usersLoginName','password', 'usersEmail', 'usersDesc', 'usersPhone', 'usersMobile', 'usersAddress','usersFullName']),
                    items: [{
                        layout: 'column',
                        items: [{
                            columnWidth: .5,
                            layout: 'form',
                            items: [{
                                xtype: 'hidden',
                                name: 'usersId',
                                anchor: '96%'
                            }, {
                                xtype: 'textfield',
                                fieldLabel: '用户名',
                                name: 'usersLoginName',
					             maxLength:40,
						         maxLengthText:'名称不能超过40个字符',
                                allowBlank: false,
                                blankText: '用户名不能为空！',
                                anchor: '96%'
                            },  {
                                xtype: 'textfield',
                                inputType: 'password',
                                fieldLabel: '密码',
                                name: 'password',
                                maxLength: 15,
                                maxLengthText: '密码长度不能超过15位!',
                                minLength: '6',
                                minLengthText: '密码长度不能少于6位!',
                                anchor: '96%'
                            },
                             {
                                xtype: 'textfield',
                                fieldLabel: '电子邮件',
                                name: 'usersEmail',
                                vtype: 'email',
                                emailText: 'email格式不正确!!',                               
                                anchor: '96%'
                            }]
                        }, {
                            columnWidth: .5,
                            layout: 'form',
                            items: [{
                                xtype: 'radiogroup',
								fieldLabel: '是否超管',
								items: [
									{boxLabel: '是', name: 'isUsersAdmin', inputValue: 1, checked: true},
									{boxLabel: '否', name: 'isUsersAdmin', inputValue: 0}
								]
                            }, {
                                xtype: 'textfield',
                                fieldLabel: '移动电话',
                                name: 'usersMobile',
                                vtype: 'alphanum',
                                alphanumMask: '只能输入数字!!',
                                regex : /^1\d{10}$/,
                                regexText:"请输入正确的手机号码!",   
                                anchor: '96%'
                            
                            }]
                        }]
                    }],
                    buttons: [{
                        id: 'btnSave',
                        text: '保 存',
                        handler: function(){
                            if (editForm.form.isValid())//客户端先验证数据
                            {
                            
                                var ok = "123";
                                editForm.form.doAction('submit', {
                                    url: 'admin/user.jhtml?method=updateUser',
                                    method: 'post',
                                    waitTitle: '请稍候',
                                    waitMsg: '正在提交表单数据，请稍候...',
                                    params: {
                                        tishi: ok
                                    },
                                    success: function(form, action){
                                    	getAlertMessage("提示","数据修改成功!",Ext.MessageBox.WARNING);
                                        this.disabled = false;
                                        this.newwin1.hide();
                                        loadDs(ds,100);
                                    },
                                    failure: formError
                                })
                            }
                        }
                        
                    }, {
                        text: '取 消',
                        handler: function(){
                            newwin1.hide();
                        }
                    }]
                });
            }
            ///编辑信息
            function showEditPanel(){
                newwin1 = new Ext.Window({
                    xtype: 'window',
                    title: '编辑信息',
                    buttonAlign: 'right',
                    closable: true,
                    layout: 'fit',
                    modal: 'true',
                    width: 630,
                    height: 280,
                    closeAction: 'hide',
                    plain: true,
                    items: new Ext.TabPanel({
                        activeTab: 0,
                        width: 590,
                        height: 260,
                        defaults: {
                            bodyStyle: 'padding:2px'
                        },
                        xtype: 'tabpanel',
                        plain: true,
                        defaults: {
                            frame: true
                        },
                        closable: true,
                        items: [{
                            title: '基本信息',
                            layout: 'column',
                            cls: 'x-plain',
                            items: [editForm]
                        }]
                    })
                
                });
                var row = grid.getSelections();
                if (row == 0) {
                	getAlertMessage("提示","请确认是否选中要编辑的信息!",Ext.MessageBox.WARNING);
                    return;
                }
                var id = row[0].get("usersId");
                var urlPath = "admin/user.jhtml?method=editUser";
                editForm.form.load({
                
                    url: urlPath,
                    params: {
                        uId: id
                    },
                    method: 'post',
                    success: function(form, action){
                    },
                    failure: formError
                    
                });
                newwin1.show();
            };
            //创建表格
            var grid = null;
            /////////////////////////
            //管理员管理
            if (windowId == 6) {
                grid = new Ext.grid.GridPanel({
                    cm: cm,
                    sm: sm,
                    border: false,
                    loadMask: { // 加载数据时出险遮罩时状态条上呈现的等待信息
                        msg: "数据加载中，请稍等..."
                    },
                    store: ds,
                    viewConfig: {
                        forceFit: true // 自动调整每列的宽度
                    },
                    bbar: golbalBBar(ds,100),
                    tbar: [{
                        text: '增加',
                        tooltip: '增加一列',
                        iconCls: 'add',
                        handler: function(){
                            showAddPanel();
                        }
                    }, '-', {
                        text: '删除',
                        tooltip: '删除选中的一列',
                        iconCls: 'remove',
                        handler: function(){
                            var rows = grid.getSelectionModel().getSelections();// 返回值为 Record 数组 
                            if (rows.length == 0) {
                            	getAlertMessage("提示","最少选择一条信息，进行删除!",Ext.MessageBox.WARNING);
                            }
                            else {
                                Ext.MessageBox.confirm('提示框', '您确定要进行该操作？', function(btn){
                                    if (btn == 'yes') {
                                    
                                        if (rows) {
                                            for (var i = 0; i < rows.length; i++) {
                                                var conn = new Ext.data.Connection();
                                                conn.request({
                                                    url: 'admin/user.jhtml?method=delUser',
                                                    params: {
                                                        uId: rows[i].get("usersId")
                                                    },
                                                    success: function(resp, opt){
                                                        ds.remove(rows[i]);
                                                    },
                                                    failure: function(resp, opt){
                                                        Ext.Msg.alert('Error', 'Unable to delete movie');
                                                    }
                                                });
                                              loadDs(ds,100);
                                            }
                                            
                                        }
                                    }
                                });
                            } // 弹出对话框警告 
                        }
                        
                       
                    }, '-', {
                        text: '修改',
                        tooltip: '修改选择的一行内容',
                        iconCls: 'add',
                        handler: function(){
                            showEditPanel();
                        }
                    }]
                })
            }
            //创建表格end
            //////////////////////////////////////////
            win = desktop.createWindow({
                id: 'user_grid_win',
                title: '管理员管理',
                width: 740,
                height: 480,
                iconCls: 'icon-grid',
                shim: false,
                animCollapse: false,
                constrainHeader: true,
                
                layout: 'fit',
                items: grid
            
            });
             loadDs(ds,100);
        }
        win.show();
    }
